package com.agung.wonogirimaps;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import com.agung.wonogirimaps.util.JSONAdapter;
import com.agung.wonogirimaps.util.Utils;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class InfoLocationActivity extends ActionBarActivity implements
		OnClickListener
{
	private static final String	TAG					= InfoLocationActivity.class
															.getName();
	private TextView			txtDesc;
	private TextView			txtAlamat;
	private int					location_id;
	private ImageView			btnMap;
	private RatingBar			rate;
	private LinearLayout		berikanRate;
	private GoogleMap			map;
	private ArrayList<String>	arrayGambar;
	private ArrayList<String>	arrayKomentar;
	private Button				btnLogout;

	private LatLng				location;
	private String				email_user;

	private ImageLoader			imageLoader;
	AlertDialog					dialogRegister;

	private JSONAdapter			json;
	private ProgressDialog		pDialog;

	AlertDialog					dialogShowRate;

	private LinearLayout		mainLayout;
	private LinearLayout		linearKomentar;
	private boolean				isRegisterSucces	= false;
	private boolean				isUserRate			= false;
	private String				pesan				= null;
	private String				title;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_info_location);

		imageLoader = ImageLoader.getInstance();
		imageLoader.init(Utils.getImgConfig(this));

		json = new JSONAdapter();

		txtDesc = (TextView) findViewById(R.id.content_description);
		txtAlamat = (TextView) findViewById(R.id.txt_location_alamat);
		rate = (RatingBar) findViewById(R.id.rating);
		linearKomentar = (LinearLayout) findViewById(R.id.linear_komentar);
		btnLogout = (Button) findViewById(R.id.btn_logout);
		if (!Utils.isUserLogin(this))
		{
			btnLogout.setVisibility(View.GONE);
		} else
		{
			btnLogout.setOnClickListener(this);
		}

		mainLayout = (LinearLayout) findViewById(R.id._linearLayout);

		berikanRate = (LinearLayout) findViewById(R.id.lin_berikan_rate);
		btnMap = (ImageView) findViewById(R.id.btnMap);

		getSupportActionBar().setIcon(android.R.color.transparent);

		btnMap.setOnClickListener(this);
		berikanRate.setOnClickListener(this);

		/**
		 * Ambil data dari activity LocationActivity
		 */
		Bundle b = getIntent().getExtras();
		if (b != null)
		{
			location_id = b.getInt(LocationActivity.TAG_ID);
			getSupportActionBar().setTitle(
					b.getString(LocationActivity.TAG_TITLE));
			txtDesc.setText(b.getString(LocationActivity.TAG_DESC));
			txtAlamat.setText(b.getString(LocationActivity.TAG_ALAMAT));
			location = new LatLng(b.getDouble(LocationActivity.TAG_LAT),
					b.getDouble(LocationActivity.TAG_LNG));
			title = b.getString(LocationActivity.TAG_TITLE);
			rate.setRating((float) b.getDouble(LocationActivity.TAG_RATE));

			if (b.getStringArrayList(LocationActivity.TAG_GAMBAR) != null)
			{
				arrayGambar = b.getStringArrayList(LocationActivity.TAG_GAMBAR);

			}

			arrayKomentar = b.getStringArrayList(LocationActivity.TAG_KOMEN);

		}

		setupMapIfNeeded();

		for (int i = 0; i < arrayKomentar.size(); i++)
		{
			TextView text = new TextView(this);
			text.setText(" -- " + arrayKomentar.get(i));
			LayoutParams par = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			par.setMargins(0, 0, 0, 5);
			text.setLayoutParams(par);
			linearKomentar.addView(text);

		}

		// Utils.TRACE(TAG, "banyak gambar ->>" + arrayGambar.size());

		if (arrayGambar != null)
		{
			if (arrayGambar.size() > 0)
			{
				for (int i = 0; i < arrayGambar.size(); i++)
				{
					ImageView imgView = new ImageView(InfoLocationActivity.this);
					imageLoader.displayImage(arrayGambar.get(i), imgView,
							Utils.getImgOpt());

					LayoutParams params = new LayoutParams(300,
							LayoutParams.MATCH_PARENT);
					params.setMargins(20, 0, 20, 0);
					imgView.setLayoutParams(params);
					mainLayout.addView(imgView);

				}
			}

		} else
		{
			ImageView imgView = new ImageView(InfoLocationActivity.this);
			// imageLoader.displayImage(arrayGambar.get(i), imgView,
			// Utils.getImgOpt());
			imgView.setBackgroundResource(R.drawable.ic_launcher);

			LayoutParams params = new LayoutParams(300,
					LayoutParams.MATCH_PARENT);
			params.setMargins(20, 0, 20, 0);
			imgView.setLayoutParams(params);
			mainLayout.addView(imgView);

		}

		Toast.makeText(this, "user login : " + Utils.isUserLogin(this),
				Toast.LENGTH_SHORT).show();

	}

	private void setupMapIfNeeded()
	{
		if (map == null)
		{
			FragmentManager fragmentManager = getSupportFragmentManager();
			SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
					.findFragmentById(R.id.map_location);
			map = supportMapFragment.getMap();

			if (map != null)
			{
				setupMap();
			}
		}
	}

	private void setupMap()
	{
		// TODO Auto-generated method stub
		map.addMarker(new MarkerOptions().position(location).title(title));
		map.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 14));

	}

	@Override
	public void onClick(View v)
	{
		if (v == btnMap)
		{
			Intent i = new Intent(android.content.Intent.ACTION_VIEW,
					Uri.parse("http://maps.google.com/maps?daddr="
							+ location.latitude + "," + location.longitude));
			startActivity(i);
		} else if (v == berikanRate)
		{
			if (Utils.isUserLogin(this))
			{
				Toast.makeText(
						InfoLocationActivity.this,
						"Login as "
								+ Utils.getDataStringSP(
										InfoLocationActivity.this, Utils.EMAIL),
						Toast.LENGTH_SHORT).show();

				new AsynCekUserRate().execute(Utils.API_CEK_USER_RATE(
						Utils.getDataStringSP(InfoLocationActivity.this,
								Utils.EMAIL), location_id));

				// cek user login
				// cek user di table rate berdasarkan id location
				// jika ada tampilkan anda sudah rate
				// jika tidak ada tampilkan rate

			} else
			{
				showLogin();
			}
		} else if (v == btnLogout)
		{
			if (Utils.isUserLogin(this))
			{
				Utils.setUserLogin(this, false);
				Toast.makeText(this, "Logout", Toast.LENGTH_SHORT).show();
				btnLogout.setVisibility(View.GONE);

				// invalidateOptionsMenu();

				// return true;
			}

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		Utils.TRACE("InfoLocation", "login " + Utils.isUserLogin(this));
		if (Utils.isUserLogin(this))
		{
			getMenuInflater().inflate(R.menu.info_location, menu);
			return true;
		} else
		{
			return false;
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		if (Utils.isUserLogin(this))
		{
			switch (item.getItemId())
			{
				case R.id.action_logout:

					if (Utils.isUserLogin(this))
					{
						Utils.setUserLogin(this, false);
						Toast.makeText(this, "Logout", Toast.LENGTH_SHORT)
								.show();

						invalidateOptionsMenu();
						return true;
					}

				default:
					return super.onOptionsItemSelected(item);
			}

		} else
		{
			return super.onOptionsItemSelected(item);

		}

	}

	@Override
	public void onBackPressed()
	{
		super.onBackPressed();
		finish();
	}

	private void showRate()
	{
		LayoutInflater mInflater = LayoutInflater.from(this);
		View v = mInflater.inflate(R.layout.pop_up_user_comment, null);
		dialogShowRate = new AlertDialog.Builder(this).create();
		dialogShowRate.setView(v);
		dialogShowRate.setTitle("Berikan rate");

		final Button btnRate = (Button) v.findViewById(R.id.btn_beri_rate);
		final EditText et_komentar = (EditText) v
				.findViewById(R.id.komentar_rate);
		final RatingBar rateUser = (RatingBar) v.findViewById(R.id.rate_user);

		final String komentar = (TextUtils.isEmpty(et_komentar.toString())) ? "null"
				: et_komentar.getText().toString();

		btnRate.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0)
			{
				new AsyncGiveRate().execute(Utils.API_RATE(
						Utils.getDataStringSP(InfoLocationActivity.this,
								Utils.EMAIL), location_id,
						rateUser.getRating(), Utils.urlEncode(et_komentar
								.getText().toString())));

			}
		});

		dialogShowRate.show();

	}

	private void showRegister()
	{
		LayoutInflater mInflater = LayoutInflater.from(this);
		View v = mInflater.inflate(R.layout.pop_up_register, null);

		dialogRegister = new AlertDialog.Builder(this).create();

		dialogRegister.setView(v);
		dialogRegister.setTitle("Registrasi");
		final Button reg = (Button) v.findViewById(R.id.btn_registrasi_user);
		final EditText email = (EditText) v
				.findViewById(R.id.input_regis_email_user);
		final EditText nama = (EditText) v
				.findViewById(R.id.input_regis_nama_user);

		reg.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v)
			{
				if (!TextUtils.isEmpty(email.getText().toString())
						&& !TextUtils.isEmpty(nama.getText().toString()))
				{
					new AsyncRegister().execute(Utils.API_REGIS_USER(email
							.getText().toString(), Utils.urlEncode(nama
							.getText().toString())));
				}
			}
		});
		dialogRegister.show();

	}

	private void showLogin()
	{
		LayoutInflater mInflater = LayoutInflater.from(this);
		View v = mInflater.inflate(R.layout.pop_up_user_login, null);

		final AlertDialog dialog = new AlertDialog.Builder(this).create();

		dialog.setView(v);
		dialog.setTitle("Silahkan Login");

		final Button btnLogin = (Button) v.findViewById(R.id.btn_login);
		final Button btnRegis = (Button) v.findViewById(R.id.btn_registrasi);
		final EditText emailUser = (EditText) v
				.findViewById(R.id.input_email_user);

		btnLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v)
			{

				if (!TextUtils.isEmpty(emailUser.getText().toString()))
				{
					// Toast.makeText(InfoLocationActivity.this,
					// "Login  " + emailUser.getText().toString(),
					// Toast.LENGTH_SHORT).show();
					email_user = emailUser.getText().toString();
					Utils.TRACE(TAG, "uri - " + Utils.API_CEK_EMAIL
							+ email_user);
					new AsynCekEmail()
							.execute(Utils.API_CEK_EMAIL + email_user);
				} else
				{
					Toast.makeText(InfoLocationActivity.this,
							"Harap isi kolom email ", Toast.LENGTH_SHORT)
							.show();
				}
				dialog.dismiss();

			}
		});
		btnRegis.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v)
			{
				Toast.makeText(InfoLocationActivity.this,
						"Register  " + emailUser.getText().toString(),
						Toast.LENGTH_SHORT).show();

				dialog.dismiss();

				showRegister();

			}
		});

		dialog.show();
	}

	private class AsynCekUserRate extends AsyncTask<String, Void, Void>
	{
		@Override
		protected Void doInBackground(String... params)
		{
			// TODO Auto-generated method stub
			JSONObject obj = json.getJSONFromURL(params[0]);
			Utils.TRACE("Info Location - CekUserRate", "url -> " + params[0]);
			try
			{
				if (obj.getInt("error") == 1)
				{
					isUserRate = true;
				} else
				{
					isUserRate = false;
				}
			} catch (Exception e)
			{
				Utils.TRACE("Info Location - CekUserRate",
						"error " + e.getMessage());
			}

			return null;
		}

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();

			pDialog = new ProgressDialog(InfoLocationActivity.this);
			pDialog.setMessage("Loading...");
			pDialog.show();
		}

		@Override
		protected void onPostExecute(Void result)
		{
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pDialog.dismiss();
			if (isUserRate)
			{
				Toast.makeText(InfoLocationActivity.this, "Anda sudah rate",
						Toast.LENGTH_SHORT).show();
			} else
			{
				showRate();
			}
		}
	}

	private class AsyncRegister extends AsyncTask<String, Void, Void>
	{
		@Override
		protected Void doInBackground(String... params)
		{
			// TODO Auto-generated method stub

			JSONObject obj = json.getJSONFromURL(params[0]);
			Utils.TRACE("InfoLoc- async", "url " + params[0]);
			try
			{

				if (obj.getInt("error") == 0)
				{
					isRegisterSucces = true;
				} else
				{
					isRegisterSucces = false;
					pesan = obj.getString("pesan");
				}

			} catch (JSONException e)
			{
				// TODO: handle exception
			}

			return null;
		}

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialogRegister.dismiss();
			if (isRegisterSucces)
			{
				Toast.makeText(InfoLocationActivity.this, "Berhasil register",
						Toast.LENGTH_SHORT).show();

				showLogin();
			} else
			{
				Toast.makeText(InfoLocationActivity.this, "User sudah ada",
						Toast.LENGTH_SHORT).show();
			}

		}

		@Override
		protected void onPostExecute(Void result)
		{
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}
	}

	private class AsynCekEmail extends AsyncTask<String, Void, Boolean>
	{
		@Override
		protected Boolean doInBackground(String... params)
		{
			JSONObject obj = json.getJSONFromURL(params[0]);

			return json.checkEmail(obj);
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			pDialog = new ProgressDialog(InfoLocationActivity.this);
			pDialog.setMessage("Login...");
			pDialog.show();

		}

		@Override
		protected void onPostExecute(Boolean result)
		{
			super.onPostExecute(result);
			pDialog.dismiss();
			Utils.TRACE(TAG, "result " + result);
			if (result)
			{
				Toast.makeText(InfoLocationActivity.this, "Login berhasil",
						Toast.LENGTH_SHORT).show();

				Utils.setUserLogin(InfoLocationActivity.this, true);
				Utils.setDataStringtoSP(InfoLocationActivity.this, Utils.EMAIL,
						email_user);
				showRate();
				btnLogout.setVisibility(View.VISIBLE);
			} else
			{
				Toast.makeText(InfoLocationActivity.this,
						"Login Gagal Email tidak ada", Toast.LENGTH_SHORT)
						.show();
			}

		}
	}

	private class AsyncGiveRate extends AsyncTask<String, Void, Boolean>
	{
		@Override
		protected Boolean doInBackground(String... params)
		{
			// TODO Auto-generated method stub
			JSONObject obj = json.getJSONFromURL(params[0]);
			return json.giveRate(obj);
		}

		@Override
		protected void onPostExecute(Boolean result)
		{
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pDialog.dismiss();
			if (result)
			{
				Toast.makeText(
						InfoLocationActivity.this,
						"Berhasil kasih rate "
								+ Utils.getDataStringSP(
										InfoLocationActivity.this, Utils.EMAIL),
						Toast.LENGTH_SHORT).show();

			}
		}

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();
			dialogShowRate.dismiss();

			if (pDialog == null)
				pDialog = new ProgressDialog(InfoLocationActivity.this);
			pDialog.setMessage("Rate....");
			pDialog.show();
		}

	}
}
